import React from 'react';

import { Modal , Button } from 'antd';
import UserForm from './UserForm';
import axios from "axios";

// const UserForm = Form.create({ name: 'normal_login' })(userForm);

let params ={};
class UserFormModal extends React.Component {
  

  constructor(props){
      super(props);
      this.state = {
        loading: false,
        visible: false,
      }
  }

  showModal = () => {
    this.setState({
      visible: true,
    });
  }

 
 
  
  handleOk = () => {
    this.setState({ loading: true });

    // console.log(this.formRef)
    this.formRef.handleSubmit()
    //获取表单Form对象 里面的属性 jsonObject
    params = this.formRef.props.form.getFieldsValue();

    //遍历JsonObject
    for (var prop in params){
      console.log("key:" + prop + " --- value:" + params[prop]);

      if(prop==='id'){
          continue;
      }
      if( params[prop]===""|| typeof(params[prop])==undefined ||typeof(params[prop])=="undefined" ){
          this.setState({ loading: false });
          return false;
      }
    }
    this.addUser();
  }

  

  clearForm=()=>{
    this.formRef.props.form.resetFields()
    // console.log( )
    //  this.formRef.resetFields();
  }

  backFill=(data)=>{
    let fileValues={'username':data.username,'password':data.password,'id':data.id};
    
    this.formRef.props.form.setFieldsValue(fileValues)
    // console.log(data)
  }

  addUser=()=>{
    let url = "http://localhost:8080/addUser";
    let jsonObject = JSON.stringify(params)   
    console.log(jsonObject)

     //设置请求头  
    axios.defaults.headers.post['Content-Type'] = 'application/json';

    axios.post(url,jsonObject)
    .then((response)=> {
      // console.log(response.data.data);
      // console.log(response)
      this.setState({ loading: false, visible: false });
      
      // console.log(this.props)
      this.props.run.getUser(1,10)
    })
    .catch(function (error) {
      // handle error
      console.log(error);
    });
  }


  handleCancel = () => {
    this.setState({ visible: false });
  }

  render() {
    const { visible, loading } = this.state;
  
    return (
     
      <div>
        {/* <Button type="primary" onClick={this.showModal}>
          Open Modal with customized footer
        </Button> */}
        <Modal
          visible={visible}
          title="新增用户"
          onOk={this.handleOk}
          closable={false}
          style={{
              width:"300px",
              height:"200px"
          }}

          onCancel={this.handleCancel}
          footer={[
            <Button key="cancel" onClick={this.handleCancel}>取消</Button>,
            <Button key="submit" type="primary" loading={loading} onClick={this.handleOk}>提交</Button>,
          ]}
        >
         <div>
            <UserForm  
              //获取子组件form属性及方法，必须使用这种写法
              wrappedComponentRef={(form) => this.formRef = form}
            />
         </div>
        </Modal>
      </div>
    );
  }
}

export default UserFormModal;